<template>
  <div class="vocabulary-list">
    <el-card class="list-card">
      <template #header>
        <CardHeader title="词汇列表">
          <template #actions>
            <el-input
              v-model="searchKeyword"
              placeholder="搜索词汇"
              clearable
              style="width: 200px; margin-right: 10px"
              @keyup.enter="applyFilter"
            >
              <template #append>
                <el-button @click="applyFilter">
                  <el-icon><Search /></el-icon>
                </el-button>
              </template>
            </el-input>
            <el-button @click="searchVocabulary" type="primary">搜索</el-button>
          </template>
        </CardHeader>
      </template>

      <div class="filter-section">
        <el-radio-group v-model="filterType" @change="applyFilter">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="ielts">雅思词汇</el-radio-button>
          <el-radio-button label="known">已掌握</el-radio-button>
          <el-radio-button label="unknown">未掌握</el-radio-button>
        </el-radio-group>
      </div>

      <div v-if="loading" class="loading">
        <el-skeleton :rows="10" animated />
      </div>

      <el-alert v-else-if="error" :title="error" type="error" show-icon :closable="false" class="error-alert" />

      <div v-else>
        <el-table :data="paginatedWords" style="width: 100%">
          <el-table-column prop="word" label="单词" width="180" />
          <el-table-column prop="trans" label="翻译" width="180" />
          <el-table-column prop="ielst" label="雅思" width="180" />
          <el-table-column prop="ok" label="掌握" width="180" />
          <el-table-column label="操作" width="300">
            <template #default="scope">
              <word-actions 
                :word="scope.row" 
                @pronunciation-play="handlePronunciationPlay"
                @status-updated="handleStatusUpdated"
              />
            </template>
          </el-table-column>
        </el-table>
        
        <div class="pagination-section">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 50, 100]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredWords.length"
          />
        </div>
      </div>
    </el-card>

    <el-dialog v-model="showWordDialog" title="单词详情" width="500px" class="word-dialog">
      <WordDetails 
        v-if="selectedWord" 
        :word="selectedWord"
        @audio-ended="onAudioEnded"
        @audio-error="onAudioError"
      >
        <template #pronunciation-controls>
          <el-button
            @click="playPronunciation('uk', selectedWord)"
            :loading="isPlaying && pronunciationType === 'uk'"
            size="small"
          >
            <el-icon><VideoPlay /></el-icon> 英式发音
          </el-button>
          <el-button
            @click="playPronunciation('us', selectedWord)"
            :loading="isPlaying && pronunciationType === 'us'"
            size="small"
          >
            <el-icon><VideoPlay /></el-icon> 美式发音
          </el-button>
          <el-button @click="stopPronunciation" size="small" v-if="isPlaying">
            <el-icon><VideoPause /></el-icon> 停止播放
          </el-button>
        </template>
        
        <template #actions>
          <WordActions 
            :word="selectedWord"
            :show-toggle-status-button="true"
            @toggle-status="toggleWordStatus"
          />
        </template>
      </WordDetails>
      <div v-else>
        <el-skeleton :rows="5" animated />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import WordActions from './WordActions.vue';
import WordDetails from './WordDetails.vue';
import CardHeader from './CardHeader.vue';
import { processWordData, filterWords } from '../utils';
import { Search, VideoPlay, VideoPause } from '@element-plus/icons-vue';
import { 
  ElPagination,
  ElTable,
  ElTableColumn,
  ElButton,
  ElIcon,
  ElInput,
  ElCard,
  ElRadioGroup,
  ElRadioButton,
  ElSkeleton,
  ElAlert,
  ElDialog,
  ElTag
} from 'element-plus';

export default {
  name: 'VocabularyList',
  components: {
    CardHeader,
    WordActions,
    WordDetails,
    ElPagination,
    ElTable,
    ElTableColumn,
    ElButton,
    ElIcon,
    ElInput,
    ElCard,
    ElRadioGroup,
    ElRadioButton,
    ElSkeleton,
    ElAlert,
    ElDialog,
    ElTag,
    Search,
    VideoPlay,
    VideoPause
  },
  data() {
    return {
      words: [],
      filteredWords: [],
      searchKeyword: '',
      filterType: 'all',
      currentPage: 1,
      pageSize: 20,
      totalWords: 0,
      loading: false,
      error: null,
      selectedWord: null,
      showWordDialog: false,
      isPlaying: false,
      pronunciationType: null,
    };
  },

  computed: {
    paginatedWords() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.filteredWords.slice(start, end);
    },
  },


  async mounted() {
    this.loadVocabulary();
    // Load total count of words
    try {
      if (typeof window.electronAPI !== 'undefined' && window.electronAPI.getWords) {
        const response = await window.electronAPI.getWords({ limit: 1, offset: 0 });
        if (response.success && response.total !== undefined) {
          this.totalWords = response.total;
        }
      }
    } catch (err) {
      console.error('Error loading total word count:', err);
    }
  },

  methods: {
    async loadVocabulary() {
      this.loading = true;
      this.error = null;

      try {
        // Check if electronAPI is available
        if (typeof window.electronAPI !== 'undefined' && window.electronAPI.getWords) {
          // If there's a search keyword, use search API instead
          if (this.searchKeyword && this.searchKeyword.trim()) {
            await this.searchVocabulary();
            return;
          }

          const response = await window.electronAPI.getWords({
            limit: this.pageSize,
            offset: (this.currentPage - 1) * this.pageSize,
          });

          if (response.success) {
            // Process the words data to match our expected format
            this.words = response.data.map(word => ({
              id: word.id,
              word: word.word,
              trans: word.trans,
              ielst: word.ielst,
              ok: word.ok,
              phonetic: word.phonetic,
              pronounce: word.pronounce,
              uk_speech: word.uk_speech,
              us_speech: word.us_speech,
            }));

            this.filteredWords = [...this.words];

            // Try to get total count if available
            if (response.total !== undefined) {
              this.totalWords = response.total;
            }
          } else {
            throw new Error(response.error || 'Failed to load vocabulary');
          }
        }
      } catch (err) {
        console.error('Error loading vocabulary:', err);
        this.error = err.message;
      } finally {
        this.loading = false;
      }
    },

    async searchVocabulary() {
      if (!this.searchKeyword.trim()) {
        // If search keyword is empty, load all words
        this.currentPage = 1;
        await this.loadVocabulary();
        return;
      }

      this.loading = true;
      this.error = null;

      try {
        // Check if electronAPI is available
        if (typeof window.electronAPI !== 'undefined' && window.electronAPI.searchVocabulary) {
          const response = await window.electronAPI.searchVocabulary(this.searchKeyword);

          if (response.success) {
            // Map the response data to match the expected format
            this.words = response.data.map(word => ({
              id: word.id,
              word: word.word,
              trans: word.trans,
              ielst: word.ielst || word.ielts || 'NO',
              ok: word.ok,
              phonetic: word.phonetic,
              pronounce: word.pronounce,
              uk_speech: word.uk_speech,
              us_speech: word.us_speech,
            }));

            this.filteredWords = [...this.words];
            this.totalWords = this.words.length;
          } else {
            throw new Error(response.error || 'Failed to search vocabulary');
          }
        }
      } catch (err) {
        console.error('Error searching vocabulary:', err);
        this.error = err.message;
      } finally {
        this.loading = false;
      }
    },

    async applyFilter() {
      this.loading = true;
      this.error = null;

      try {
        // Check if electronAPI is available
        if (typeof window.electronAPI !== 'undefined' && window.electronAPI.getWords) {
          // If there's a search keyword, use search API instead
          if (this.searchKeyword) {
            const response = await window.electronAPI.searchWords(this.searchKeyword.trim());

            if (response.success) {
              let result = response.data.map(word => processWordData(word));

              // Apply type filter
              result = filterWords(result, this.filterType);

              this.words = result;
              this.filteredWords = [...this.words];
              this.totalWords = this.words.length;
              this.currentPage = 1;
            } else {
              throw new Error(response.error || 'Failed to search vocabulary');
            }
          } else {
            // No search keyword, load all words with pagination
            const response = await window.electronAPI.getWords({
              limit: this.pageSize,
              offset: (this.currentPage - 1) * this.pageSize,
            });

            if (response.success) {
              let result = response.data.map(word => processWordData(word));

              // Apply type filter
              result = filterWords(result, this.filterType);

              this.words = result;
              this.filteredWords = [...this.words];

              // Try to get total count if available
              if (response.total !== undefined) {
                this.totalWords = response.total;
              }
            } else {
              throw new Error(response.error || 'Failed to load vocabulary');
            }
          }
        }
      } catch (err) {
        console.error('Error applying filter:', err);
        this.error = err.message;
      } finally {
        this.loading = false;
      }
    },

    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.loadVocabulary();
    },

    handlePronunciationPlay(data) {
      console.log('Playing pronunciation:', data);
    },

    handleStatusUpdated(data) {
      console.log('Word status updated:', data);
      // Could trigger a refresh or other actions if needed
    },
      
    async handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.loadVocabulary();
    },

    viewWordDetails(row) {
      this.selectedWord = row;
      this.showWordDialog = true;
    },

    // Centralized method to get toggle button text
    getToggleButtonText(status) {
      return status === 'YES' ? '标记未掌握' : '标记已掌握';
    },

    // Centralized method to show success messages
    showSuccessMessage(word, newStatus) {
      const action = newStatus === 'YES' ? '标记为掌握' : '取消掌握';
      this.$message.success(`已${action}: ${word}`);
    },

    // Centralized method to show error messages
    showErrorMessage(message) {
      this.$message.error(message);
    },

    async toggleWordStatus(word) {
      try {
        // Check if electronAPI is available
        if (typeof window.electronAPI !== 'undefined' && window.electronAPI.updateKnownStatus) {
          const newStatus = word.ok === 'YES' ? 'NO' : 'YES';
          const response = await window.electronAPI.updateKnownStatus({
            word: word.word,
            status: newStatus,
          });

          if (response.success) {
            word.ok = newStatus;
            const action = newStatus === 'YES' ? '掌握' : '取消掌握';
            this.$message.success(`已${action}: ${word.word}`);
          } else {
            throw new Error(response.error || 'Failed to update word status');
          }
        }
      } catch (err) {
        console.error('Error updating word status:', err);
        this.$message.error('更新单词状态失败: ' + err.message);
      }
    },

    isPronunciationAvailable(word) {
      return pronunciationUtils.isPronunciationAvailable(word);
    },

    async playPronunciation(type, word) {
      const result = await pronunciationUtils.playPronunciation(
        word, 
        type, 
        {
          success: (msg) => this.$message.success(msg),
          error: (msg) => this.$message.error(msg),
          warning: (msg) => this.$message.warning(msg)
        }
      );
      
      if (result.success) {
        this.isPlaying = true;
        this.pronunciationType = type;
      }
    },

    stopPronunciation() {
      // Since we're using a new Audio object in the utility, we can't stop it directly
      // In a real implementation, we would keep a reference to the audio object
      this.isPlaying = false;
      this.pronunciationType = null;
      this.$message.success('已停止播放');
    },

    onAudioEnded() {
      this.isPlaying = false;
      this.pronunciationType = null;
      console.log('Audio playback completed');
    },

    onAudioError(err) {
      this.isPlaying = false;
      this.pronunciationType = null;
      console.error('Audio playback error:', err);
      this.showErrorMessage('音频播放出错: ' + err.message);
    },
  },
};
</script>

<style scoped>
.vocabulary-list {
  max-width: 1200px;
  margin: 0 auto;
}

.list-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.filter-section {
  margin: 20px 0;
}

.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}


.error-alert {
  margin: 20px 0;
}
</style>
